package top.melody.ecommerce.webapps.www.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler;
import top.melody.ecommerce.webapps.www.base.AssertContext;
import top.melody.ecommerce.webapps.www.base.UserSession;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;

/**
 * @author: blentle
 * @group: rd
 * @createdate: 2016/11/11 9:55
 * @mail: blentle.huan.ren@gmail.com
 * @description: 获取用户基本消息，购车等，用于页面展示
 * @since:1.0
 */
public class AccountProfileInterceptor extends HandlerInterceptorAdapter {

    private static final Logger logger = LoggerFactory.getLogger(AccountProfileInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //不拦截静态资源
        if (handler instanceof DefaultServletHttpRequestHandler)
            return true;
        try {
            //1.从session中获取,
            //2.如果没有,从Cookie中获取，
            //3.cookie中没有，则没有
            UserSession currentUser = AssertContext.getCurrentAccount(request);
            request.setAttribute("currentUser",currentUser);
            return true;
        } catch (UnsupportedEncodingException e) {
            logger.error("occurred exception when encoding cookie key and value", e);
        }
        return true;
    }

}
